import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

public class TCPCopyPictureServer {
    public static void main(String[] args) {
        try {
            // 启动服务器，打开指定的端口
            ServerSocket serverSocket = new ServerSocket(8888);
            Socket server = null;
            while (true) {
                // 等待客户端连接，连接后返回一个新的 Socket
                // 客户端每连接到服务器一次，服务器就会创建一个新的socket 与客户端通信
                server = serverSocket.accept();
                // System.out.println(server);

                // step0、获取输入输出流
                OutputStream outputStream = server.getOutputStream();
                // 将输出字节流转换为输出字符流
                OutputStreamWriter outputStreamWriter = new OutputStreamWriter(outputStream);
                // 启动输出缓冲区
                BufferedWriter bufferedWriter = new BufferedWriter(outputStreamWriter);

                InputStream inputStream = server.getInputStream();
                InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
                BufferedReader bufferedReader = new BufferedReader(inputStreamReader);


                // step1 服务器给客户端发送文件名
                String fileName = "gitee.jpg";
                bufferedWriter.write(fileName);
                bufferedWriter.write("\r\n");
                bufferedWriter.flush();
                // step2 服务器给客户端发送文件大小
                File file = new File(fileName);
                // 获取文件的字节数
                long size = file.length();
                bufferedWriter.write(Long.toString(size));
                bufferedWriter.write("\r\n");
                bufferedWriter.flush();

                FileInputStream fileInputStream = new FileInputStream(fileName);
                BufferedInputStream bufferedInputStream = new BufferedInputStream(fileInputStream);
                byte[] bytes = new byte[8192];
                int length;
                while ((length = bufferedInputStream.read(bytes)) != -1) {
                    outputStream.write(bytes, 0, length);
                }

                fileInputStream.close();

                String info = bufferedReader.readLine();
                System.out.println(info);

                // step 关闭所有资源
                bufferedWriter.close();
                outputStreamWriter.close();
                outputStream.close();

                bufferedReader.close();
                inputStreamReader.close();
                inputStream.close();

                server.close();
            }

            // serverSocket.close();

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
